package tv.youxing.android.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.androidemojidemo.ParseEmojiMsgUtil;
import com.example.androidemojidemo.SelectFaceHelper;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import tv.youxing.android.Interface.LoadMoreListener;
import tv.youxing.android.Interface.UpRefUpdateListener;
import tv.youxing.android.R;
import tv.youxing.android.adapter.DynamicDetailsAdapter;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.Custom_up_down_refresh_ListView;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.entity.DynamicDetailsPingLunModel;
import tv.youxing.android.entity.SendPingLunModel;
import tv.youxing.android.entity.ViewPlayerPingLunModel;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static com.mob.MobSDK.getContext;


/**
 * 说说评论界面
 */
public class DynamicDetailsActivity extends BaseActivity {

    @BindView(R.id.ivIcon)
    CircleImageView ivIcon;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvContent)
    TextView tvContent;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.ivPraise)
    ImageView ivPraise;
    @BindView(R.id.tvPraise)
    TextView tvPraise;
    @BindView(R.id.tvComment)
    TextView tvComment;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.lv)
    Custom_up_down_refresh_ListView lv;
    @BindView(R.id.iv_Expression)
    ImageView ivExpression;


    int resource_type = -1;
    int resource_id = -1;
    int user_id = -1;


    boolean isRef = false;
    int curPageCount = 0;//当前页数

    ViewPlayerPingLunModel allData;
    List<ViewPlayerPingLunModel.ResultBean.DataBean> mDataBeanList = new ArrayList<>();

    SendPingLunModel mSendPingLunModel;//发表评论

    @BindView(R.id.et_content)
    EditText et_content;//发表表情
    TextView textView;
    int PingLunCount = 0;
    boolean isRefHead = true;


    private DynamicDetailsPingLunModel mDynamicDetailsPingLunModel;
    private DynamicDetailsAdapter mDynamicDetailsAdapter;


    private SelectFaceHelper mFaceHelper;
    private Button mFaceBtn;
    private View addFaceToolView;
    private boolean isVisbilityFace;
    private EditText mEditMessageEt;
    private Button mSentBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_details);
        ButterKnife.bind(this);


        addFaceToolView = (View) findViewById(R.id.add_tool);
        mEditMessageEt = (EditText) findViewById(R.id.txtMessage);
        mSentBtn = (Button) findViewById(R.id.btnSend);
        mFaceBtn = (Button) findViewById(R.id.btn_to_face);
        mFaceBtn.setOnClickListener(faceClick);
        mSentBtn.setOnClickListener(sendClick);
        mEditMessageEt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isVisbilityFace = false;
                addFaceToolView.setVisibility(View.GONE);
                return false;
            }
        });

        mDynamicDetailsPingLunModel = (DynamicDetailsPingLunModel) getIntent().getSerializableExtra("data");

        initView();
        setOnClickListener();
        mSwipeRefreshLayout.setRefreshing(true);
        initHead();
        loadDatas(null);

    }

    private void initView() {

        mEditMessageEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                    String msg = mEditMessageEt.getText().toString();
                    if (!msg.equals("")) {
                        String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), DynamicDetailsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
                        sendPingLun(msgStr);
                        mEditMessageEt.setText("");
                        PingLunCount++;
                        L.d("count:" + PingLunCount);
                        tvComment.setText(PingLunCount+"");
                    }
                }
                return true;
            }
        });


        mDynamicDetailsAdapter = new DynamicDetailsAdapter(this, mDataBeanList);
        lv.setAdapter(mDynamicDetailsAdapter);
    }


    private void setOnClickListener() {
        /**
         * 下拉刷新
         */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mDataBeanList.clear();
                        isRef = false;
                        curPageCount = 0;
                        loadDatas(null);
                    }
                }, 1500);
            }
        });

        /**
         * 上拉加载更多
         */
        lv.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {


                        isRef = true;
                        loadDatas(new UpRefUpdateListener() {
                            @Override
                            public void upRef(int count) {
                                if (count > 0) {
                                    lv.loadMoreComplete();
                                } else {
                                    lv.loadMoreEnd();
                                }

                            }
                        });

//
                    }
                }, 1500);

            }
        });
    }


    /**
     * 发送评论
     */
    void sendPingLun(final String str) {


        if (!UtilTools.LoginJudge()) {
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }

        //post请求简洁版实现
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(this, AppConst.TOKEN, ""));
        params.put("content", str);
        params.put("resource_type", 2);
        params.put("resource_id", mDynamicDetailsPingLunModel.getTweet_id());
//        params.put("resource_id", 13);

        L.d("resource_id:" + mDynamicDetailsPingLunModel.getTweet_id());

        RxVolley.post(StaticClass.SendPingLun, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mSendPingLunModel = GsonUtils.GsonToBean(t, SendPingLunModel.class);

                if (mSendPingLunModel.getCode() == AppConst.TOKENERROR) {
                    DynamicDetailsActivity.this.startActivity(new Intent(DynamicDetailsActivity.this,LoginActivity.class));
                    return;
                }

                if (mSendPingLunModel.getCode() == 200) {
                    CustomToast.INSTANCE.showToast("发表成功");
                    ViewPlayerPingLunModel.ResultBean.DataBean bean = new ViewPlayerPingLunModel.ResultBean.DataBean();
                    ViewPlayerPingLunModel.ResultBean.DataBean.PublishUserBean bean_user = new ViewPlayerPingLunModel.ResultBean.DataBean.PublishUserBean();
                    bean_user.setAvatar(ShareUtils.getString(DynamicDetailsActivity.this, AppConst.AVATER, ""));
                    bean_user.setUsername(ShareUtils.getString(DynamicDetailsActivity.this, AppConst.USERNAME, ""));
                    bean.setContent(str);
                    bean.setUpdated_at(UtilTools.getCurTime());
                    bean.setPublish_user(bean_user);
                    mDataBeanList.add(bean);
                    initSomething();
                } else {
                    CustomToast.INSTANCE.showToast("发表失败");
                    L.d("发表失败:"+t);
                }
            }
        });
    }


    void loadDatas(final UpRefUpdateListener listener) {
        //post请求简洁版实现
        HttpParams params = new HttpParams();
        curPageCount++;
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(this, AppConst.TOKEN, ""));
        params.put("resource_type", 2);
        params.put("resource_id", mDynamicDetailsPingLunModel.getTweet_id());
        if (UtilTools.LoginJudge()) {
            params.put("user_id", ShareUtils.getInt(this, AppConst.USERID, 0));
        }
        params.put("page", curPageCount);

        RxVolley.post(StaticClass.AlbumDetailURL, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                allData = GsonUtils.GsonToBean(t, ViewPlayerPingLunModel.class);


                if (allData.getCode() == AppConst.TOKENERROR) {
                    DynamicDetailsActivity.this.startActivity(new Intent(DynamicDetailsActivity.this,LoginActivity.class));
                    return;
                }

                if (allData.getCode() == 200) {
                    mDataBeanList.addAll(allData.getResult().getData());




                    initSomething();

                    mSwipeRefreshLayout.setRefreshing(false);

                    if (listener != null) {
                        listener.upRef(allData.getResult().getData().size());
                    }


                }

                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    //初始化说说列表
    void initSomething() {
        mDynamicDetailsAdapter.notifyDataSetChanged();
    }


    /**
     * 初始化头像信息
     */
    void initHead() {
        PicassoUtils.loadImageView(this, mDynamicDetailsPingLunModel.getPublish_user().getAvatar(), ivIcon);
        tvName.setText(mDynamicDetailsPingLunModel.getPublish_user().getUsername());
        tvContent.setText(mDynamicDetailsPingLunModel.getContent());
        tvTime.setText(mDynamicDetailsPingLunModel.getPublish_time());
        tvPraise.setText(mDynamicDetailsPingLunModel.getLike_count());

        L.d("pinglunCount:" + mDynamicDetailsPingLunModel.getComment_count());

        PingLunCount = Integer.parseInt(mDynamicDetailsPingLunModel.getComment_count());
        tvComment.setText("评论数:" + PingLunCount);

        if (mDynamicDetailsPingLunModel.getIs_like() == 1) {
            ivPraise.setSelected(true);
            if (Integer.parseInt(mDynamicDetailsPingLunModel.getLike_count()) <= 0) {
                tvPraise.setText("1");
            }
        } else {
            ivPraise.setSelected(false);
            ivPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DianZhan();
                }
            });
        }


    }


    boolean is_biaoqing_show = false;

    @OnClick({R.id.iv_Expression, R.id.ivPraise})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_Expression:


                if (is_biaoqing_show) {
                    findViewById(R.id.ll_biaoqing).setVisibility(View.GONE);
                } else {
                    findViewById(R.id.ll_biaoqing).setVisibility(View.VISIBLE);
                }
                is_biaoqing_show = !is_biaoqing_show;
                break;
            case R.id.ivPraise:
                if (mDynamicDetailsPingLunModel.getIs_like() == 0) {
                    DianZhan();
                }
                break;
        }
    }


    /**
     * 点赞
     */
    void DianZhan() {

        if (!UtilTools.LoginJudge()) {
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("resource_id", mDynamicDetailsPingLunModel.getTweet_id());
        params.put("resource_type", 2);

        RxVolley.post(StaticClass.DianZan, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);


                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    DynamicDetailsActivity.this.startActivity(new Intent(DynamicDetailsActivity.this,LoginActivity.class));
                    return;
                }

                CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                if (dianZhanModel.getCode() == 200) {
                    if (dianZhanModel.getResult().getIs_like() == 1) {
                        ivPraise.setSelected(true);
                        tvPraise.setText((Integer.parseInt(mDynamicDetailsPingLunModel.getLike_count()) + 1) + "");
                    } else {
                        ivPraise.setSelected(false);
                        tvPraise.setText((Integer.parseInt(mDynamicDetailsPingLunModel.getLike_count())) + "");
                    }
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("点赞失败");
                }
            }
        });
    }



    SelectFaceHelper.OnFaceOprateListener mOnFaceOprateListener = new SelectFaceHelper.OnFaceOprateListener() {
        @Override
        public void onFaceSelected(SpannableString spanEmojiStr) {
            if (null != spanEmojiStr) {
                mEditMessageEt.append(spanEmojiStr);
            }
        }

        @Override
        public void onFaceDeleted() {
            int selection = mEditMessageEt.getSelectionStart();
            String text = mEditMessageEt.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    mEditMessageEt.getText().delete(start, end);
                    return;
                }
                mEditMessageEt.getText().delete(selection - 1, selection);
            }
        }

    };

    View.OnClickListener faceClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            L.d("click");

            if (null == mFaceHelper) {
                mFaceHelper = new SelectFaceHelper(DynamicDetailsActivity.this, addFaceToolView);
                mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
            }
            if (isVisbilityFace) {
                isVisbilityFace = false;
                addFaceToolView.setVisibility(View.GONE);
            } else {
                isVisbilityFace = true;
                addFaceToolView.setVisibility(View.VISIBLE);
                hideInputManager(DynamicDetailsActivity.this);
            }
        }
    };
    View.OnClickListener sendClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String msg = mEditMessageEt.getText().toString();
            if (msg.equals("")) {
                return;
            }
            String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), DynamicDetailsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
            sendPingLun(msgStr);
            mEditMessageEt.setText("");
        }
    };

    // 隐藏软键盘
    public void hideInputManager(Context ct) {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) ct)
                    .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
    }

}
